//
//  THPopView.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//

#import "THPopView.h"
#import "THPopViewManager.h"
#import "THPopMaskViewController.h"
#import "THCurrentVCWindowsManager.h"
@interface THPopView ()<UIGestureRecognizerDelegate>
@property(nonatomic, retain,readwrite) UIWindow *window;
@property (nonatomic,retain) UIView *backgroundView;
@property (nonatomic,retain) UIView *contentView;
@property (nonatomic,assign) BOOL showAniamte;

@end

@implementation THPopView

- (instancetype)initWithFrame:(CGRect)frame
                  contentView:(UIView*)contentView{
    return [self initWithFrame:frame
                   contentView:contentView
                     alignType:THPopViewAlignCenterType];
}
- (instancetype)initWithFrame:(CGRect)frame
                  contentView:(UIView*)contentView
                    alignType:(THPopViewAlignType)alignType{
    NSCParameterAssert(contentView);
    if (self = [super initWithFrame:frame]) {
        _contentView = contentView;
        [self commit];
        _alignType = alignType;
    }
    return self;
}
- (void)commit{
    _backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.8];
    _duration        = 0.2;
    _alignType       = THPopViewAlignCenterType;
    _enableTouch     = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                          action:@selector(handleGesture:)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
}
- (void)showInView{
    if (self.willShowBlock) {
        self.willShowBlock(self);
    }
    self.backgroundView = [[UIView alloc] initWithFrame:self.bounds];
    self.backgroundView.backgroundColor = self.backgroundColor;
    [self addSubview:self.backgroundView];
    self.contentView.frame = [self prepareFrame];
    [self.backgroundView addSubview:self.contentView];

    THPopMaskViewController *viewController = [[THPopMaskViewController alloc] init];
    viewController.statusBarHidden = [UIApplication sharedApplication].statusBarHidden;
    viewController.statusBarStyle  = [UIApplication sharedApplication].statusBarStyle;
    UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    if ([UIDevice currentDevice].systemVersion.intValue == 9) { // Fix bug for keyboard in iOS 9
        window.windowLevel = CGFLOAT_MAX;
    } else {
        window.windowLevel = UIWindowLevelAlert;
    }
    window.rootViewController = viewController;
    [window makeKeyAndVisible];
    self.window = window;
    [viewController.view addSubview:self];
    self.userInteractionEnabled = NO;// quick click
    if (!self.showAniamte) {
        self.contentView.frame = [self didFinishFrame];
        if (self.didShowBlock) {
            self.didShowBlock(self);
        }
    }else{
        [UIView animateWithDuration:self.duration delay:0 usingSpringWithDamping:0.8
              initialSpringVelocity:0.2 options:UIViewAnimationOptionCurveLinear
             animations:^{
             self.contentView.frame = [self didFinishFrame];
        } completion:^(BOOL finished) {
            self.userInteractionEnabled = YES;
            if (self.didShowBlock) {
                self.didShowBlock(self);
            }
        }];
    }
}
- (void)show
{
    [self showAniamte:YES];
}
- (void)showAniamte:(BOOL)animate{
   //supportSinglePop for only one pop View
    [[[THCurrentVCWindowsManager shareManager] currentWindow] endEditing:YES];

    _showAniamte = animate;
    BOOL isExist = [[THPopViewManager shareInstance] isExistPopView];
    if (!self.supportSinglePop || !isExist) [self showInView];
    if (self.supportSinglePop) [[THPopViewManager shareInstance] pushView:self];
}
- (void)dismiss{
    [self dismissAniamte:YES];
}
- (void)dismissAniamte:(BOOL)animate{
    if (self.willDismissBlock) {
        self.willDismissBlock(self);
    }
    if (!animate) {
       if ([[THPopViewManager shareInstance] lastPopView] == self) {
           [[THPopViewManager shareInstance] popView:self];
           if ([[THPopViewManager shareInstance] isExistPopView]) {
               [[[THPopViewManager shareInstance] lastPopView ] showInView];
           }
       }else{
           if (self.supportSinglePop) [[THPopViewManager shareInstance] popView:self];
       }
       if (self.didDismissBlock) {
           self.didDismissBlock(self);
       }
       self.window.rootViewController = nil;
       self.window.hidden = YES;
       self.window = nil;
       [self removeFromSuperview];
    }else{
        [UIView animateWithDuration:self.duration delay:0
        options:UIViewAnimationOptionCurveLinear animations:^{
            self.contentView.frame = [self prepareFrame];
        } completion:^(BOOL finished) {
            if ([[THPopViewManager shareInstance] lastPopView] == self) {
                [[THPopViewManager shareInstance] popView:self];
                if ([[THPopViewManager shareInstance] isExistPopView]) {
                    [[[THPopViewManager shareInstance] lastPopView ] showInView];
                }
            }else{
                if (self.supportSinglePop) [[THPopViewManager shareInstance] popView:self];
            }
            if (self.didDismissBlock) {
                self.didDismissBlock(self);
            }
            self.window.rootViewController = nil;
            self.window.hidden = YES;
            self.window = nil;
            [self removeFromSuperview];
        }];
    }
}
- (void)handleGesture:(UIGestureRecognizer*)gestureRecognizer{
    CGPoint touchPoint = [gestureRecognizer locationInView:self];
    if (!self.enableTouch) return;
    if (CGRectContainsPoint(self.contentView.frame,touchPoint)) return;
    [self dismiss];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:_contentView]) return NO;
    return YES;
}
#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer.view isDescendantOfView:_contentView]) return NO;
    return YES;
}
- (CGRect)prepareFrame{
    return CGRectMake((CGRectGetWidth(self.frame) - CGRectGetWidth(self.contentView.frame))*0.5,CGRectGetHeight(self.frame), CGRectGetWidth(self.contentView.frame),CGRectGetHeight(self.contentView.frame));
}
- (CGRect)didFinishFrame{
    switch (_alignType) {
        case THPopViewAlignBottomType:
            return CGRectMake((CGRectGetWidth(self.frame) - CGRectGetWidth(self.contentView.frame))*0.5, (CGRectGetHeight(self.frame) - CGRectGetHeight(self.contentView.frame)) + self.offsetY , CGRectGetWidth(self.contentView.frame),CGRectGetHeight(self.contentView.frame));
            break;
        case THPopViewAlignCenterType:
            return CGRectMake((CGRectGetWidth(self.frame) - CGRectGetWidth(self.contentView.frame))*0.5, ((CGRectGetHeight(self.frame)-CGRectGetHeight(self.contentView.frame)))*0.5 + self.offsetY, CGRectGetWidth(self.contentView.frame),CGRectGetHeight(self.contentView.frame));
                break;
        default:
            return CGRectMake((CGRectGetWidth(self.frame) - CGRectGetWidth(self.contentView.frame))*0.5, (CGRectGetHeight(self.frame)-CGRectGetHeight(self.contentView.frame)) + self.offsetY , CGRectGetWidth(self.contentView.frame),CGRectGetHeight(self.contentView.frame));
            break;
    }
}

@end
